/**
 * Created by Toma on 2016/8/22.
 * 一个疯狂的小球球
 */

// 推理过程
function initial() {
  // 0. 准备
  var x = 10, y = 10, direction = 1, WIDTH, HEIGHT, RADIUS = 10;

  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  WIDTH = canvas.width;
  HEIGHT = canvas.height;

  // 1. 小球动起来
  requestAnimationFrame(function step() {
    // 判断方向，决定小球的坐标
    if (direction == 1) {
      x++;
      y++;

      if (y >= HEIGHT - RADIUS) {
        direction = 2;
      }
      if (x >= WIDTH - RADIUS) {
        direction = 4;
      }
    } else if (direction == 2) {
      x++;
      y--;

      if (x >= WIDTH - RADIUS) {
        direction = 3;
      }
      if (y <= RADIUS) {
        direction = 1;
      }
    } else if (direction == 3) {
      x--;
      y--;

      if (y <= RADIUS) {
        direction = 4;
      }
      if (x <= RADIUS) {
        direction = 2;
      }
    } else if (direction == 4) {
      x--;
      y++;

      if (x <= RADIUS) {
        direction = 1;
      }
      if (y >= HEIGHT - RADIUS) {
        direction = 3;
      }
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.fillStyle = 'red';
    ctx.arc(x, y, RADIUS, 0, Math.PI * 2, true);
    ctx.fill();
    ctx.closePath();

    requestAnimationFrame(step);
  });
}


// 其二
function init() {
  // 0. 准备
  var x = 10, y = 10, yy = 4, xx = 4, WIDTH, HEIGHT, RADIUS = 10;

  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  WIDTH = canvas.width;
  HEIGHT = canvas.height;

  // 1. 小球动起来
  requestAnimationFrame(function step() {
    // 判断横向边界
    if(x < RADIUS || x >= WIDTH - RADIUS){
      xx = -xx;
    }
    if(y < RADIUS || y >= HEIGHT -RADIUS){
      yy = -yy;
    }

    x += xx;
    y += yy;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.fillStyle = 'red';
    ctx.arc(x, y, RADIUS, 0, Math.PI * 2, true);
    ctx.fill();
    ctx.closePath();

    requestAnimationFrame(step);
  });
}

window.addEventListener('load', init, false);